import asyncio
from version_comparator import MCPVersionComparator

class MCPVersionNegotiator:
    def __init__(self):
        # 支持的版本列表 按时间顺序排序
        self.supported_versions= ["2023-09-15", "2024-12-01", "2025-06-18"] 
        self.comparator = MCPVersionComparator()
    async def get_server_versions(self,server_url):
        return ["2024-12-01", "2025-06-18"]  
    async def negotiate_versions(self,server_versions):
        common_version = self.comparator.get_latest_common_version(
            self.supported_versions,
            server_versions
        )
        if common_version:
            print(f"版本协商成功:{common_version}")
            return common_version
        else:
            print(f"版本协商失败")
            return None

    async def establish_connection(self,server_url,negotiated_version):
        print(f"使用版本{negotiated_version}与{server_url}建立连接")
    async def graceful_disconnect(self):
        print(f"版本不兼容，优雅的断开连接")
    async def connect_to_server(self,server_url):
        try:
           # 异步获取服务器的支持的版本列表
           server_versions = await self.get_server_versions(server_url)
           negotiated_version = await self.negotiate_versions(server_versions)
           if negotiated_version:
               await self.establish_connection(server_url,negotiated_version)
               return True
           else:
               await self.graceful_disconnect()
               return False
        except  Exception as e:
            print(str(e))    

async def main():
    mcpVersionNegotiator=MCPVersionNegotiator()
    success = await mcpVersionNegotiator.connect_to_server("ws://localhost:8080")
    if success:
        print('连接已经建立')
    else:
        print("连接失败")    



asyncio.run(main())        